import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useIntl, useRequest } from '@umijs/max';
import { useDebounceFn } from 'ahooks';
import { Button, Col, Divider, Form, message, Row } from 'antd';
import {
  type ForwardRefRenderFunction,
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import { fetchPreEntity } from '@/apis/ygt';
import {
  useCartData,
  useCostData,
  useDealData,
  useReceiveData,
} from '@/pages/order/components/CreateForm/CreateForm.data';
import { ColumnMap } from '@/pages/order/Order.data';
import './createForm.less';
import { FormattedMessage } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import { createCustomer, getCustomerById } from '@/apis/customer';
import type { CustomerInfo } from '@/pages/customer/index.data';

interface CreateFormProps {
  reload?: any;
}

export type CreateFormRef = {
  handleEdit: (id: string) => void;
};

const CreateForm: ForwardRefRenderFunction<CreateFormRef, CreateFormProps> = (
  props,
  ref,
) => {
  const { reload } = props;

  const [messageApi, contextHolder] = message.useMessage();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const { run, loading } = useRequest(createCustomer, {
    manual: true,
    onSuccess: () => {
      messageApi.success('添加成功');
      reload?.();
    },
    onError: () => {
      messageApi.error('添加失败，请重试!');
    },
  });

  const [readonly, setReadonly] = useState(false);
  const [form] = Form.useForm();

  const updateFormField = (key: string, value: any) => {
    const fieldName = ColumnMap[key].dataIndex;
    if (!form.getFieldValue(fieldName)) {
      form.setFieldValue(fieldName, value);
    }
  };

  const debouncedSerialChange = useDebounceFn(
    async (val: string) => {
      const res = await fetchPreEntity(val);
      if (res.code === 200) {
        const detail: any = res.data || {};
        const vesselVoyageInfo: any = detail.vesselVoyageInfo || {};
        const billInfo: any =
          detail.billInfoList?.length > 0 ? detail.billInfoList[0] : {};
        const packInfo: any = detail.packInfo || {};
        [
          ['driverName', detail.driverName], // 司机
          ['driverPhone', detail.mobile], // 司机手机
          ['vesselName', vesselVoyageInfo.vesseleName], // 船名
          ['voyage', vesselVoyageInfo.voyage], // 航次
          ['billNumber', billInfo.blno], // 提单号
          ['containerNumber', billInfo.ctnno], // 箱号
          ['sealNumber', packInfo.sealno], // 封条号
          ['containerType', packInfo.sizetype], // 箱型
          ['transitPort', packInfo.tranport], // 中转港
          ['shippingLine', `${packInfo.operator}(${packInfo.operatorcode})`], // 船公司
          ['openingTime', vesselVoyageInfo.ctnstart], // 开港时间
          ['portCutoff', vesselVoyageInfo.ctnend], // 截港时间
          ['pickupYard', packInfo.cpcode], // 提箱场站-出运码头
          ['customerPickupYard', packInfo.cpcode], // 客户提箱场站-出运码头
          ['contractNumber', packInfo.costcono], // 合同号
        ].forEach(([key, value]) => {
          updateFormField(key, value);
        });
      }
    },
    { wait: 500 },
  );

  const dealData = useDealData();
  const carData = useCartData();
  const costData = useCostData();

  const receiveDate = useReceiveData(
    dealData.total,
    carData.total,
    costData.total,
  );

  const handleSubmit = async (value: any) => {
    await run(value);
    console.log('[mlog]--->reload', reload);
    reload && reload();
    return true;
  };

  const [open, setOpen] = useState(false);

  const modelRef = useRef(null);

  const handleEdit = (id: string) => {
    setOpen(true);
    getCustomerById(id).then((res) => {
      if (res.code === 200) {
        const record = res.data;
        form.setFieldsValue(record);
        setCurrentRecord(record);
      }
    });
  };

  // 向父组件暴露方法
  useImperativeHandle(ref, () => ({
    handleEdit,
  }));
  const [currentRecord, setCurrentRecord] = useState<
    CustomerInfo | undefined
  >();
  const [isViewMode, setIsViewMode] = useState(false);
  const handleModalClose = () => {
    setOpen(false);
    setCurrentRecord(undefined);
  };
  return (
    <>
      {contextHolder}
      <ModalForm
        title={
          isViewMode
            ? '查看客户信息'
            : currentRecord
              ? '编辑客户信息'
              : '新建客户'
        }
        form={form}
        modalProps={{
          destroyOnClose: true,
        }}
        layout={'horizontal'}
        width={800}
        open={open}
        onOpenChange={setOpen}
        onFinish={handleSubmit}
        initialValues={currentRecord}
        trigger={
          <Button type="primary" icon={<PlusOutlined />}>
            <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        }
        submitter={
          isViewMode
            ? {
                render: () => [
                  <Button key="close" onClick={handleModalClose}>
                    关闭
                  </Button>,
                ],
              }
            : undefined
        }
      >
        <Divider>基本信息</Divider>
        <ProFormText hidden name="id"></ProFormText>
        <Row gutter={16}>
          <Col span={12}>
            <ProFormText
              name="customerFullName"
              label="客户全称"
              placeholder="请输入客户全称"
              rules={[{ required: true, message: '请输入客户全称' }]}
              disabled={isViewMode}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="shorthandCode"
              label="速记码"
              placeholder="请输入速记码"
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <ProFormText
              name="region"
              label="所属地区"
              placeholder="请选择所属地区"
              disabled={isViewMode}
            />
          </Col>

          <Col span={12}>
            <ProFormSelect
              name="branchOffice"
              label="分公司"
              placeholder="请输入分公司"
              valueEnum={{
                总部: '总部',
                分公司: '分公司',
              }}
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <ProFormSwitch
              name="isPeer"
              label="是否同行"
              disabled={isViewMode}
              layout={'horizontal'}
            />
          </Col>
          <Col span={12}>
            <ProFormSwitch
              name="needInvoice"
              label="是否需要开票"
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Divider>联系信息</Divider>
        <Row gutter={16}>
          <Col span={12}>
            <ProFormText
              name="contactPhone"
              label="联系电话"
              placeholder="请输入联系电话"
              disabled={isViewMode}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="mobilePhone"
              label="手机号码"
              placeholder="请输入手机号码"
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <ProFormText
              name="email"
              label="电子邮箱"
              placeholder="请输入电子邮箱"
              disabled={isViewMode}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="customerDispatcher"
              label="客户派单员"
              placeholder="请输入客户派单员"
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Divider>财务信息</Divider>
        <Row gutter={16}>
          <Col span={12}>
            <ProFormDigit
              name="costTaxRate"
              label="成本税率"
              placeholder="请输入成本税率"
              min={0}
              max={100}
              fieldProps={{
                addonAfter: '%',
              }}
              disabled={isViewMode}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit
              name="receivableTaxRate"
              label="应收税率"
              placeholder="请输入应收税率"
              min={0}
              max={100}
              fieldProps={{
                addonAfter: '%',
              }}
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <ProFormText
              name="taxpayerId"
              label="纳税人识别号"
              placeholder="请输入纳税人识别号"
              disabled={isViewMode}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="settlementMethod"
              label="结算方式"
              placeholder="请选择结算方式"
              valueEnum={{
                月结: '月结',
                现结: '现结',
                预付: '预付',
                到付: '到付',
              }}
              disabled={isViewMode}
            />
          </Col>
        </Row>

        <Divider>其他信息</Divider>
        <ProFormTextArea
          name="remarks"
          label="备注"
          placeholder="请输入备注信息"
          disabled={isViewMode}
        />
      </ModalForm>
    </>
  );
};

export default forwardRef(CreateForm);
